<?php

namespace app\service;

use app\model\SysSetting;
use mailer\tp6\Mailer;
use think\facade\Config;

class EmailService
{
    protected $subject = '询盘提醒邮件';
    protected $sendAccount = null;
    protected $sendPass = null;
    protected $sendType = null;
    protected $getAccount = [];

    protected $ali = [
        'host'  => 'smtp.qiye.aliyun.com',
        'port'  => '465',
        'security'  => 'ssl',
    ];

    protected $office = [
        'host'  => 'smtp.office365.com',
        'port'  => '587',
        'security'  => 'tls',
    ];

    protected $wangyi = [
        'host'  => 'smtp.163.com',
        'port'  => '465',
        'security'  => 'ssl',
    ];

    protected $qq = [
        'host'  => 'smtp.qq.com',
        'port'  => '465',
        'security'  => 'ssl',
    ];

    public function __construct()
    {
        $this->setConfig();
    }

    public function setConfig()
    {
        $Setting = new SysSetting();
        $emailConfig = $Setting->getAllCustomData(['group'=>'email','status'=>1],'id desc','id,title,value,group')['data'];
        if(!empty($emailConfig)){
            $emailConfig = getColumnForKeyArray($emailConfig,'title');
            $this->sendAccount = $emailConfig['email_send_account']['value'];
            $this->sendPass = $emailConfig['email_password']['value'];
            $this->sendType = $emailConfig['email_type']['value'];
            array_push($this->getAccount,$emailConfig['email_get_account']['value']);
        }
    }

    /**
     * @throws \mailer\lib\Exception
     */
    public function sendEmail($content,$account = [])
    {
        $customConfig = [
            'pass'  => $this->sendPass,
            'name'  => $this->sendAccount,
            'addr'  => $this->sendAccount,
        ];
        array_push($this->getAccount ,$account);

        if($this->sendType == '365'){
            $commonConfig = $this->office;
        }else if($this->sendType == '163'){
            $commonConfig = $this->wangyi;
        }else{
            $tmpKey = $this->sendType;
            $commonConfig = $this->$tmpKey;
        }
        $emailConfig = array_merge($commonConfig,$customConfig);
        Config::set($emailConfig,'mail');
        $mailer = Mailer::instance();
        if(!empty($this->getAccount)){
            foreach($this->getAccount as $val){
                $mailer->to($val)
                    ->subject($this->subject)
                    ->html($content)
                    ->send();
            }
        }
    }

}